<template>
  <div id="essayUpload">
    <el-form :model="essayData" :rules="fromRules" ref="form">
      <el-form-item prop="content">
        <div>
          随笔内容
          <el-input type="textarea" v-model="essayData.content" placeholder="请输入随笔内容" autosize></el-input>
        </div>
      </el-form-item>
      <el-form-item>
        <div>
          心情：
          <el-select v-model="essayData.mood" placeholder="请选择心情">
            <el-option v-for="item in moodData" :key="item.id" :label="item.moodName" :value="item.id"></el-option>
          </el-select>
          <el-avatar :src="'https://bokey.oss-cn-shenzhen.aliyuncs.com/img/mood/' + essayData.mood + '.png'"></el-avatar>
        </div>
      </el-form-item>
      <el-form-item prop="time">
        时间：
        <el-date-picker type="date" placeholder="请选择日期" id="el_input" v-model="essayData.time"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <div>
          权限：
          <span id="authorityText">私有</span>
          <el-switch v-model="essayData.authority" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
        </div>
      </el-form-item>
      <el-form-item>
        选择随笔图片(可选)：
        <el-upload ref="uploadImg" class="upload-demo" action="" :http-request="filesRequest" :limit="1" :multiple="false"
          :auto-upload="false" :on-exceed="fileExceed" :file-list="fileList" list-type="picture" accept=".jpg, .png">
          <el-button size="small" type="primary" style="margin-left: 20px;">选择随笔图片</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <el-button @click="submit" type="success" style="z-index: 20;">提交</el-button>
    <div class="moodTips" :id="moodTipsShowId">{{ moodMsg[essayData.mood] }}</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      essayData: {
        content: '',
        mood: '',
        authority: false,
        time: new Date(),
      }, // 随笔内容
      moodData: [], // 心情数据
      fileList: [], // 图片list
      moodMsg: {
        1: '不要伤心啦，会好起来的~',
        2: '好好休息叭~',
        3: '内心的平静是最好的良药(*^_^*)',
        4: 'doki~doki~',
        5: '快乐最重要o(*￣▽￣*)ブ',
        6: '相信我，都会好起来的~',
        7: '气死啦(╯▔皿▔)╯',
        8: 'wow~美好不期而遇呢',
      }, // 默认心情的小tip
      moodTipsShowId: '', // 默认心情的小tip的动态标签id
      fromRules: {
        content: [
          { required: true, message: '请输入随笔内容', trigger: 'blur' },
        ],
        time: [
          { required: true, message: '请输入随笔时间', trigger: 'change' },
        ],
      }, // 表单规则
    }
  },
  methods: {
    // 获取所有心情
    getAllMood() {
      this.$axios({
        method: 'post',
        url: '/mood/login/getAllMood'
      }).then(res => {
        this.moodData = res.data
        // 将mood设置为第一个数据的id
        this.essayData.mood = res.data[0].id
      })
    },
    // 提交事件
    submit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          // 触发心情小提示
          this.moodTipsShowId = 'TipsShow'
          window.setTimeout(() => { // 两秒后关闭
            this.moodTipsShowId = ''
          }, 2000)
          // 上传
          if (this.$refs.uploadImg.uploadFiles.length > 0) {
            this.$refs.uploadImg.submit(); // 有图片，触发http-request的回调函数
          } else {
            this.toBackUploadEssay(false, null) // 没有图片，直接发送请求
          }
        } else {
          this.$message({
            message: '请完善再提交哦~',
            type: 'error',
            showClose: true,
          })
        }
      })
    },
    // 提交心情图片及心情名称
    filesRequest(param) {
      if (this.getfileName(param.file.name) != '.jpg' && this.getfileName(param.file.name) != '.png') {
        this.$message({
          message: '请选择文件格式为jpg或png的图片作为心情图片',
          type: 'error',
          showClose: true,
        })
        return
      }
      this.toBackUploadEssay(true, param)
    },
    // 工具函数：发送请求给后端上传随笔，参数说明：1.是否有图片 2.图片文件
    toBackUploadEssay(imgExit, param) {
      // 准备数据
      let data = new FormData()
      data.append("content", this.essayData.content)
      if (imgExit) data.append("file", param.file)
      data.append("moodId", this.essayData.mood)
      data.append("authority", this.essayData.authority ? 1 : 0)
      data.append("time", new Date(this.essayData.time))
      this.$axios({
        method: 'post',
        url: '/essay/login/uploadEssay',
        data: data,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(res => {
        if (res.data) {
          this.$message({
            message: '提交成功',
            type: 'success',
            showClose: true,
          })
        } else {
          this.$message({
            message: '提交失败！出现错误了X.X',
            type: 'error',
            showClose: true,
          })
        }
      })
    },
    // 文件个数过多事件
    fileExceed() {
      this.$message({
        showClose: true,
        type: 'error',
        message: '只能上传一个文件哦~',
      })
    },
    // 工具函数：获取文件后缀工具函数
    getfileName(filename) {
      // 转换为小写
      const pos = filename.toLowerCase().lastIndexOf('.')
      let suffix = ''
      if (pos !== -1) {
        suffix = filename.substring(pos)
      }
      return suffix
    }
  },
  mounted() {
    this.getAllMood()
  }
}
</script>

<style lang="scss" scoped>
#essayUpload {
  display: flex;
  flex-direction: column;
  padding: 20px;
}

#authorityText {
  margin-right: 10px;
}

.moodTips {
  text-align: center;
  transform: translateY(-20px);
  transition: all .5s;
  opacity: 0;
  font-size: $font-size-small;
  font-weight: $font-weight-medium;
}

#TipsShow {
  opacity: 1;
  transform: translateY(10px);
  opacity: 1;
}
</style>
<style scoped="scoped" scope>
/deep/.el-textarea__inner {
  min-height: 60px !important;
}

/deep/.el-textarea__inner,
/deep/.el-input__inner {
  background-color: #202020;
  text-align: center;
  color: #fff;
}

/* 图片选择按钮以及图片展示框 */
.el-button--primary {
  background-color: #202020;
  border-color: #fff;
}

/deep/.el-upload-list--picture .el-upload-list__item {
  background-color: #202020;
}

/* 头像框(心情图片) */
/deep/.el-avatar {
  background: rgba(0, 0, 0, 0);
  vertical-align: top;
  margin-left: 20px;
}
</style>